<template>
  <div class="oa-callback-container">
    <van-loading  size="24px">正在处理OA登录...</van-loading>
    <div  class="error-message">
      <van-icon name="warning-o" size="24px" />
      <p>{{ error }}</p>
      <van-button type="primary" @click="goToLogin">返回登录页</van-button>
    </div>
  </div>
</template>

<script>
import { mapActions } from "vuex"
import { Notify } from 'vant'

export default {
  name: 'OACallback',
  data() {
    return {
      processing: true,
      error: null
    }
  },
  async mounted() {
    try {
      // 解析URL中的code
      const urlParams = new URLSearchParams(window.location.search)
      const code = urlParams.get('code')

      if (!code) {
        alert('未收到OA认证码')
        throw new Error('未收到OA认证码')
      }

      // 获取OA配置
      const oaBaseUrl = window._CONFIG['authURL']
      //const clientId = getEnv('VUE_APP_OA_CLIENT_ID') || 'eb728e3137ca33e6'
      const clientId = 'eb728e3137ca33e6'
      //const clientSecret = getEnv('VUE_APP_OA_CLIENT_SECRET') || 'b3fb6c4d456628de5aee032ca92753e9'
      const clientSecret =  'b3fb6c4d456628de5aee032ca92753e9'

      // 1. 获取access_token
      const tokenResponse = await this.$http.post(`${oaBaseUrl}/oauth2.0/accessToken`, {
        client_id: clientId,
        client_secret: clientSecret,
        redirect_uri: `${window.location.origin}/app/oa-callback`,
        code: code,
        grant_type: 'authorization_code'
      })

      const accessToken = tokenResponse.data.access_token
      if (!accessToken) {
        throw new Error('获取OA访问令牌失败')
      }

      // 2. 获取用户信息
      const userResponse = await this.$http.get(`${oaBaseUrl}/oauth2.0/profile`, {
        headers: {
          Authorization: `Bearer ${accessToken}`
        }
      })

      const userInfo = userResponse.data

      // 3. 使用OA用户信息登录系统
      const loginParams = {
        username: userInfo.id,
        oaData: userInfo.attributes
      }

      await this.mLogin(loginParams)

      Notify({ type: 'success', message: 'OA登录成功!' })
      this.$router.push({ path: "/main/home" })

    } catch (error) {
      console.error('OA登录失败:', error)
      this.error = error.message || 'OA认证失败，请尝试其他登录方式'
      this.processing = false
    }
  },
  methods: {
    ...mapActions(['mLogin']),
    goToLogin() {
      this.$router.push({
        path: '/login',
        query: { oa_callback: true } // 防止重定向循环
      })
    }
  }
}
</script>

<style scoped>
.oa-callback-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100vh;
  padding: 20px;
}

.error-message {
  text-align: center;
  color: #f44;
}

.error-message p {
  margin: 15px 0;
}
</style>
